package cn.wwxula.user.config;

import cn.wwxula.common.json.JacksonObjectMapper;
import cn.wwxula.user.constant.UserConstant;
import cn.wwxula.user.interceptor.UserHolderInterceptor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author liyang23
 * @date 2024/12/17 19:24
 **/
@Slf4j
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Resource
    UserHolderInterceptor userHolderInterceptor;

    /**
     * 注册用户态保存拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userHolderInterceptor)
                .excludePathPatterns(UserConstant.USER_REGISTER_URL)
                .excludePathPatterns(UserConstant.USER_LOGIN_URL)
                .excludePathPatterns(UserConstant.USER_RESET_PASSWORD_URL)
                .excludePathPatterns(UserConstant.USER_GETCODE_URL)
                .addPathPatterns("/userInfo/**")
                .addPathPatterns("/user/**");
    }

    /**
     * 处理 Bean 对象与 JSON的转换，会添加一个转换器，可以处理对象中 LocalDateTime这一类消息的转换
     *
     * @param converters 消息转换器集合
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("正在添加自定义JSON转换器");
        //创建消息转换器
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        //创建并设置自定义对象转换器
        converter.setObjectMapper(new JacksonObjectMapper());
        //将自定义消息转换器添加进框架中
        converters.addFirst(converter);
    }
}

